﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using LEShortcut.Commands;

namespace LEShortcut.Models.Views.Pages
{
    public class SettingViewModel
    {
        private readonly ICommand _saveConfigCommand;

        public SettingViewModel()
        {
            Context = new SettingViewContext();
            _saveConfigCommand = new SaveConfigCommand();
            Init();
        }

        public SettingViewContext Context { get; set; }

        public ICommand SaveConfigCommand
        {
            get { return _saveConfigCommand; }
        }

        private void Init()
        {
            var cache = Application.Current.Resources["cache"] as AppCache;
            Debug.Assert(cache != null, "cache != null");
            Context.Config = cache.Config;
            Context.CultureDictionary = cache.Cultures;
            if (cache.Languages != null && cache.Languages.Any()) Context.LanguageDictionary = cache.Languages;
            else
            {
                Context.LanguageDictionary = new Dictionary<string, string>();
                foreach (var entry in Context.CultureDictionary)
                {
                    var culture = new CultureInfo(entry.Key);
                    Context.LanguageDictionary.Add(culture.NativeName, culture.Name);
                }
                cache.Languages = Context.LanguageDictionary;
            }
        }

        public void LanSelectionChanged(object obj, EventArgs e)
        {
            var control = obj as ComboBox;
            if (control != null)
            {
                var cn = (string) control.SelectedValue;
                var culture = new CultureInfo(cn);
                if (Context.CultureDictionary.ContainsKey(culture.LCID))
                {
                    Context.Config.Language = cn;
                }
            }
        }
    }
}